﻿using System;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using SystemX.Infrastructure;
using SystemX.Web.Infrastructure;

namespace SystemX.Web.Handlers
{
	/// <summary>
	/// SWFUpload handler
	/// </summary>
	public class SWFUploadHandler : IHttpHandler, IRequiresSessionState
	{
		#region IHttpHandler Members

		public bool IsReusable
		{
			get { return true; }
		}

		public void ProcessRequest(HttpContext context)
		{
			var _params = new SWFParamData(context);
			RequestParams = _params;
			var response = "{'hi':null}";
			SWFUploadResponseData data = new SWFUploadResponseData();
            BOMessager msg = new BOMessager();

			OnSWFUpload(context, x =>
			{
				msg = x;
			});

			data.Load(msg);

            response = data.ToJSONStr();
			context.Response.Clear();
			context.Response.ContentType = "application/json;charset=utf-8";
			context.Response.Write(response);
			context.Response.End();
		}
		#endregion

		#region member variables
		/// <summary>
		/// Request params
		/// </summary>
		SWFParamData RequestParams { get; set; }
		public int MaxImgSize { get { return 1024; } }

		void OnSWFUpload(HttpContext context,Action<BOMessager> callback) {
			if (null != Uploaded) {
				Uploaded(this, new SWFUploadEventArgs {
					Context=context,
					Callback=callback,
					Params=RequestParams
				});
			}
		}

		public static event EventHandler<SWFUploadEventArgs> Uploaded;
		public static void AddObservers(params Action<object, SWFUploadEventArgs>[] obs)
		{
			if (obs == null || obs.Length == 0) return;
			obs.ToList().ForEach(x => {
				Uploaded += new EventHandler<SWFUploadEventArgs>(x);
			});
		}
		#endregion
	}
}
